<template>
  <v-navigation-drawer
    v-model="open"
    fixed
    right
    v-bind="$attrs"
    v-on="$listeners"
    id="drawer"
  >
  <template
    v-if="title"
    v-slot:prepend
  >
    <div class="d-flex justify-space-between align-center">
      <v-subheader>{{ title }}</v-subheader>
      <v-btn icon @click="cancel">
        <v-icon>mdi-close</v-icon>
      </v-btn>
    </div>
  </template>
  <v-divider
    v-if="$slots.prepend || title"
  />
  <div class="drawer-scorll-height" :style="{'height': `calc(100vh - ${height}px)`}">
    <slot />
  </div>
  <template
    v-if="actions || $slots.append"
    v-slot:append
  >
    <v-divider />
    <div class="d-flex justify-center py-3">
      <v-btn class="mr-5" @click="cancel">{{ cancelText || $t('actions.cancel') }}</v-btn>
      <v-btn color="primary" @click="$emit('ok')">{{ okText || $t('actions.ok') }}</v-btn>
    </div>
  </template>
  </v-navigation-drawer>
</template>
<script>
  export default {
    name: 'MaterialDrawer',

    inheritAttrs: false,

    props: {
      value: Boolean,
      title: String,
      actions: Boolean,
      okText: String,
      cancelText: String
    },

    data() {
      return {
        height: undefined
      }
    },

    computed: {
      open: {
        get() {
          return this.value
        },
        set(bool) {
          this.$emit('input', bool)
          this.setScorllHeight()
          if(!bool && bool != this.open) {
            this.$emit('cancel')
          }
        }
      }
    },

    methods: {
      cancel() {
        this.open = false
      },
      setScorllHeight() {
        let headerEl = document.querySelector('#drawer .v-navigation-drawer__prepend')
        let footerEl = document.querySelector('#drawer .v-navigation-drawer__append')
        let headerH = 0
        let footerH = 0
        if (headerEl) {
          headerH = headerEl.clientHeight
        }
        if (footerEl) {
          footerH = footerEl.clientHeight
        }
        this.height = headerH + footerH
      }    
    }
  }
</script>

<style lang="scss" scoped>
  #drawer .drawer-scorll-height {
    max-height: 100vh;
    overflow: auto;
  }
</style>
